<template>
  <div class="site-wrapper">
    <div class="header clearfix">
      <el-button type="primary" v-if="isManager" size="small" :disabled="isObserver" @click="createCustomer">新增</el-button>
      <el-button type="primary" v-if="isManager" size="small" :disabled="multipleSelection.length === 0 || isObserver" @click="delCustomer(false)">批量删除</el-button>
      <el-button type="primary" v-if="isManager" size="small" :disabled="multipleSelection.length === 0 || isObserver" @click="giveCustomer">转交</el-button>
      <el-button type="primary" v-if="isManager" size="small" :disabled="isObserver" @click="clickFileBtn">导入</el-button>
      <el-button type="primary" v-if="isManager" size="small" :disabled="isObserver" @click="exportExcel">导出</el-button>
      <el-button type="primary" v-if="isManager" size="small" :disabled="isObserver" @click="downloadTemplate">下载导入模板</el-button>
      <input type="file" style="display: none;" ref="uploadbtn" @change="uploadCustomer($event)">
      <div class="filter" @click="showFilter = true;"><img src="../../../../assets/livolobim/filter.png" alt="">搜索</div>
      <div class="mask" v-if="showFilter" @click="showFilter = false;"></div>
      <div class="filter-wrapper" v-if="showFilter">
        <span class="filter-arrow"></span>
        <span class="filter-white"></span>
        <div class="filter-header">搜索</div>
        <el-form :model="filterData" style="padding: 0 16px;" label-width="100px">
          <el-form-item label="客户名称">
            <el-input v-model="filterData.search"></el-input>
          </el-form-item>
          <el-form-item label="客户编号">
            <el-input v-model="filterData.customerCode"></el-input>
          </el-form-item>
          <el-form-item label="客户来源">
            <el-select v-model="filterData.fromPlatId" style="width: 100%;"  placeholder="请选择">
              <el-option v-for="item in khly" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="客户类型">
            <el-select v-model="filterData.customerType" style="width: 100%;"  placeholder="请选择">
              <el-option v-for="item in khlx" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="客户状态">
            <el-select v-model="filterData.customerStatus" style="width: 100%;"  placeholder="请选择">
              <el-option v-for="item in khzt" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所属国家">
            <el-select :filterable="true" style="width: 100%;" v-model="filterData.countryCode">
              <el-option v-for="item in gjdq" :key="item.code" :label="item.name + '(' + item.code + ')'" :value="item.code"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button style="float:right;margin-right: 16px;" size="small" type="primary" @click="getFilterData">确定</el-button>
          <el-button style="float:right;margin-right: 16px;" size="small" @click="resetData">重置</el-button>
        </div>
      </div>
    </div>
    <div class="data-wrapper">
      <el-table :height="tableHeight" @sort-change="sortList" :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column align="center" type="selection" width="55"></el-table-column>
        <el-table-column align="center" prop="name" label="客户名称" min-width="100"></el-table-column>
        <el-table-column align="center" prop="code" label="自定义客户编号" min-width="120"></el-table-column>
        <el-table-column align="center" prop="fromPlat" label="客户来源" min-width="100"></el-table-column>
        <el-table-column align="center" prop="customerTypeName" label="客户类型" min-width="100"></el-table-column>
        <el-table-column align="center" prop="customerStatusName" label="客户状态" min-width="100"></el-table-column>
        <el-table-column align="center" prop="countryName" label="地区" min-width="100"></el-table-column>
        <el-table-column sortable="time" align="center" prop="lastFollowDate" label="最后跟进时间" min-width="130">
          <template slot-scope="scope">
            {{scope.row.lastFollowDate}}({{scope.row.dateDiff}}天)
          </template>
        </el-table-column>        
        <el-table-column v-if="isManager" label="操作" min-width="200" align="center">
          <template slot-scope="scope">
            <el-button @click="editCustomer(scope.row.id, true)" type="text" size="small">查看</el-button>
            <el-button v-if="!isObserver" @click="editCustomer(scope.row.id, false)" type="text" size="small">编辑</el-button>
            <el-button @click="endEmail(scope.row.id, true)" type="text" size="small">发送邮箱</el-button>
            <el-button v-if="!isObserver" @click="delCustomer(scope.row.id)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="page"
        :page-sizes="[15, 30, 50, 100]"
        :page-size="pageSize"
        :total="totalPage"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>
      <el-dialog width="1000px" :visible.sync="showForm" :show-close="true">
        <div slot="title">
          <h2 style="text-align:center;margin-bottom:0;">{{form.id? isCheck? '查看': '编辑': '创建'}}客户</h2>
        </div>
        <div class="form-wrapper" style="padding: 0 20px;">
          <el-form ref="form" :model="form" label-width="135px">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item style="font-weight: bold;" label="客户名称：">
                  <span slot="label">客户名称<span style="color: red;">*</span>：</span>
                  <el-input :disabled="isCheck" v-model="form.name"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item style="font-weight: bold;" label="自定义客户编号：">
                  <el-input disabled v-model="form.code"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item style="font-weight: bold;" label="业务类型：">
                  <el-select :disabled="isCheck" style="width: 100%;" v-model="form.businessType" placeholder="请选择业务类型">
                    <el-option v-for="item in ywlx" :key="item.id" :label="item.name" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item style="font-weight: bold;" label="拥有人：">
                  <div class="select-btn" v-if="form.salorId">
                    <span>{{form.salorName}}</span>
                    <div class="del" v-if="!isCheck" @click="delMember">移除</div>
                  </div>
                  <div v-if="!form.salorId" @click="selectDingUsers()" class="select-btn">请选择</div>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item style="font-weight: bold;" label="客户简称：">
                  <el-input :disabled="isCheck" v-model="form.aliaName"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item style="font-weight: bold;" label="设立时间：">
                  <el-date-picker :disabled="isCheck" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" v-model="form.createDate" style="width: 100%;"></el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item style="font-weight: bold;" label="客户类型：">
                  <span slot="label">客户类型<span style="color: red;">*</span>：</span>
                  <el-select :disabled="isCheck" style="width: 100%;" v-model="form.customerType" placeholder="请选择客户类型">
                    <el-option v-for="item in khlx" :key="item.id" :label="item.name" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item style="font-weight: bold;" label="客户来源：">
                  <el-select :disabled="isCheck" style="width: 100%;" v-model="form.fromPlatId" placeholder="请选择客户来源">
                    <el-option v-for="item in khly" :key="item.id" :label="item.name" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item style="font-weight: bold;" label="国家地区：">
                  <span slot="label">国家地区<span style="color: red;">*</span>：</span>
                  <el-select :disabled="isCheck" :filterable="true" style="width: 100%;" v-model="form.countryCode" placeholder="请选择国家地区">
                    <el-option v-for="item in gjdq" :key="item.code" :label="item.name + '(' + item.code + ')'" :value="item.code"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
             <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item style="font-weight: bold;" label="客户等级：">
                  <span slot="label">客户等级<span style="color: red;">*</span>：</span>
                  <el-select :disabled="isCheck" style="width: 100%;" v-model="form.levelCode" placeholder="请选择客户等级">
                    <el-option v-for="item in khdj" :key="item.code" :label="item.name" :value="item.code"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item style="font-weight: bold;" label="客户状态：">
                  <el-select :disabled="isCheck" style="width: 100%;" v-model="form.customerStatus" placeholder="请选择客户状态">
                    <el-option v-for="item in khzt" :key="item.id" :label="item.name" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <!-- <el-col :span="8">
                <el-form-item style="font-weight: bold;" label="时区：">
                  <el-select :disabled="isCheck" style="width: 100%;" v-model="form.timeZone" placeholder="请选择时区">
                    <el-option v-for="item in sq" :key="item.name" :label="item.name" :value="item.name"></el-option>
                  </el-select>
                </el-form-item>
              </el-col> -->
              <el-col :span="8">
                <el-form-item style="font-weight: bold;" label="城市：">
                  <el-input :disabled="isCheck" v-model="form.city"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item style="font-weight: bold;" label="所属公司：">
                  <el-select
                    v-model="form.companyId"
                    filterable
                    :disabled="isCheck"
                    remote
                    reserve-keyword
                    placeholder="请输入公司名称"
                    :remote-method="fetchSSGS"
                    @change="handleSelect"
                    :loading="loading">
                    <el-option
                      v-for="item in ssgs"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item style="font-weight: bold;" label="公司地址：">
                  <el-input disabled :value="form.companyEntity && form.companyEntity.address"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item style="font-weight: bold;" label="公司网址：">
                  <el-input disabled :value="form.companyEntity && form.companyEntity.webSite"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="16">
                <el-form-item style="font-weight: bold;" label="共享成员：">
                  <div @click="selectShareMember()" v-if="!isCheck" class="select-btn">添加</div>
                  <div class="select-btn" v-for="(member, idx) in shareMember.names" :key="idx">
                    <span>{{member}}</span>
                    <div class="del" v-if="!isCheck" @click="delShareMember(idx)">移除</div>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20" v-if="!form.id">
              <el-col :span="24">
                <el-form-item style="font-weight: bold;" label="联系方式：">
                  <el-row v-for="(contact,idx) in form.contactList" :gutter="24" :key="idx" :style="{'margin-top': idx > 0 ? '5px': '0px'}">
                    <el-col :span="5" style="padding: 0;" :style="{'margin-left': idx > 0 ? '12px': '0px'}">
                      <el-select style="width: 100%;" v-model="contact.contactType" placeholder="请选择联系方式">
                        <el-option v-for="item in lxfs" :key="item.id" :label="item.name" :value="item.id"></el-option>
                      </el-select>
                    </el-col>
                    <el-col :span="18">
                      <el-input v-model="contact.content"></el-input>
                    </el-col>
                    <i v-if="(form.contactList.length -1) === idx" @click="addItem(idx)" class="el-icon-circle-plus" style="cursor:pointer;"></i>
                    <i v-else @click="removeItem(idx)" class="el-icon-remove" style="cursor:pointer;"></i>
                  </el-row>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item style="font-weight: bold;" label="备注：">
                  <el-input type="textarea" :disabled="isCheck" :rows="3" placeholder="请输入备注信息" v-model="form.remark"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20" v-if="form.id">
              <el-col :span="24" style="position:relative;">
                <div v-if="(!isCheck || activeName === 'fourth') && !isObserver" @click="openAddForm" style="position:absolute;right:30px;top: 15px;color: #409EFF;cursor:pointer;z-index: 2;">新增</div>
                <el-tabs v-model="activeName" style="padding-left: 40px;padding-bottom: 30px;">
                  <el-tab-pane label="收货地址" name="first">
                    <el-table :data="form.addrList" border style="width: 100%;">
                      <el-table-column align="center" type="index" label="序号" width="60"></el-table-column>
                      <el-table-column prop="recName" align="center" label="名字" min-width="100">
                        <template slot-scope="scope">
                          <span v-if="!scope.row.isEdit">{{scope.row.recName}}</span>
                          <el-input v-if="scope.row.isEdit" v-model="scope.row.recName"></el-input>
                        </template>
                      </el-table-column>
                      <el-table-column prop="recAddr" align="center" label="地址" min-width="100">
                        <template slot-scope="scope">
                          <span v-if="!scope.row.isEdit">{{scope.row.recAddr}}</span>
                          <el-input v-if="scope.row.isEdit" v-model="scope.row.recAddr"></el-input>
                        </template>
                      </el-table-column>
                      <el-table-column prop="postalCode" align="center" label="邮编" min-width="100">
                        <template slot-scope="scope">
                          <span v-if="!scope.row.isEdit">{{scope.row.postalCode}}</span>
                          <el-input v-if="scope.row.isEdit" v-model="scope.row.postalCode"></el-input>
                        </template>
                      </el-table-column>
                      <el-table-column prop="company" align="center" label="公司信息" min-width="100">
                        <template slot-scope="scope">
                          <span v-if="!scope.row.isEdit">{{scope.row.company}}</span>
                          <el-input v-if="scope.row.isEdit" v-model="scope.row.company"></el-input>
                        </template>
                      </el-table-column>
                      <el-table-column prop="phone" align="center" label="电话" min-width="100">
                        <template slot-scope="scope">
                          <span v-if="!scope.row.isEdit">{{scope.row.phone}}</span>
                          <el-input v-if="scope.row.isEdit" v-model="scope.row.phone"></el-input>
                        </template>
                      </el-table-column>
                      <el-table-column prop="taxNo" align="center" label="税号" min-width="100">
                        <template slot-scope="scope">
                          <span v-if="!scope.row.isEdit">{{scope.row.taxNo}}</span>
                          <el-input v-if="scope.row.isEdit" v-model="scope.row.taxNo"></el-input>
                        </template>
                      </el-table-column>
                      <el-table-column v-if="!isCheck" label="操作" min-width="100" align="center">
                        <template slot-scope="scope">
                          <el-button v-if="!scope.row.isEdit" @click="scope.row.isEdit = true;" type="text" size="small">编辑</el-button>
                          <!-- <el-button v-if="scope.row.isEdit" @click="saveSale(scope.row)" type="text" size="small">保存</el-button> -->
                          <el-button @click="delSale(scope.row, scope.$index)" type="text" size="small">删除</el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-tab-pane>
                  <el-tab-pane label="联系方式" name="second">
                    <el-table :data="form.contactList" border style="width: 100%;">
                      <el-table-column align="center" type="index" label="序号" width="60"></el-table-column>
                      <el-table-column prop="contactTypeName" align="center" label="方式" min-width="100">
                        <template slot-scope="scope">
                          <el-select :disabled="!scope.row.isEdit" style="width: 100%;" v-model="scope.row.contactType" placeholder="请选择联系方式">
                            <el-option v-for="item in lxfs" :key="item.id" :label="item.name" :value="item.id"></el-option>
                          </el-select>
                        </template>
                      </el-table-column>
                      <el-table-column prop="content" align="center" label="内容" min-width="100">
                        <template slot-scope="scope">
                          <span v-if="!scope.row.isEdit">{{scope.row.content}}</span>
                          <el-input v-if="scope.row.isEdit" v-model="scope.row.content"></el-input>
                        </template>
                      </el-table-column>
                      <el-table-column v-if="!isCheck" label="操作" min-width="100" align="center">
                        <template slot-scope="scope">
                          <el-button v-if="!scope.row.isEdit" @click="scope.row.isEdit = true;" type="text" size="small">编辑</el-button>
                          <!-- <el-button v-if="scope.row.isEdit" @click="saveSale(scope.row)" type="text" size="small">保存</el-button> -->
                          <el-button @click="delSale(scope.row, scope.$index)" type="text" size="small">删除</el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-tab-pane>
                  <el-tab-pane label="银行账户" name="third">
                    <el-table :data="form.accList" border style="width: 100%;">
                      <el-table-column align="center" type="index" label="序号" width="60"></el-table-column>
                      <el-table-column prop="bankName" align="center" label="银行全名" min-width="100">
                        <template slot-scope="scope">
                          <span v-if="!scope.row.isEdit">{{scope.row.bankName}}</span>
                          <el-input v-if="scope.row.isEdit" v-model="scope.row.bankName"></el-input>
                        </template>
                      </el-table-column>
                      <el-table-column prop="bankName" align="center" label="银行识别码(必填)" min-width="140">
                        <template slot-scope="scope">
                          <span v-if="!scope.row.isEdit">{{scope.row.swiftCode}}</span>
                          <el-input v-if="scope.row.isEdit" v-model="scope.row.swiftCode"></el-input>
                        </template>
                      </el-table-column>
                      <el-table-column prop="enName" align="center" label="英文名" min-width="100">
                        <template slot-scope="scope">
                          <span v-if="!scope.row.isEdit">{{scope.row.enName}}</span>
                          <el-input v-if="scope.row.isEdit" v-model="scope.row.enName"></el-input>
                        </template>
                      </el-table-column>
                      <el-table-column prop="bankAddr" align="center" label="银行地址" min-width="100">
                        <template slot-scope="scope">
                          <span v-if="!scope.row.isEdit">{{scope.row.bankAddr}}</span>
                          <el-input v-if="scope.row.isEdit" v-model="scope.row.bankAddr"></el-input>
                        </template>
                      </el-table-column>
                      <el-table-column prop="bankTel" align="center" label="银行电话" min-width="100">
                        <template slot-scope="scope">
                          <span v-if="!scope.row.isEdit">{{scope.row.bankTel}}</span>
                          <el-input v-if="scope.row.isEdit" v-model="scope.row.bankTel"></el-input>
                        </template>
                      </el-table-column>
                      <el-table-column prop="accountName" align="center" label="开户名" min-width="100">
                        <template slot-scope="scope">
                          <span v-if="!scope.row.isEdit">{{scope.row.accountName}}</span>
                          <el-input v-if="scope.row.isEdit" v-model="scope.row.accountName"></el-input>
                        </template>
                      </el-table-column>
                      <el-table-column prop="remark" align="center" label="备注" min-width="100">
                        <template slot-scope="scope">
                          <span v-if="!scope.row.isEdit">{{scope.row.remark}}</span>
                          <el-input v-if="scope.row.isEdit" v-model="scope.row.remark"></el-input>
                        </template>
                      </el-table-column>
                      <el-table-column v-if="!isCheck" label="操作" min-width="100" align="center">
                        <template slot-scope="scope">
                          <el-button v-if="!scope.row.isEdit" @click="scope.row.isEdit = true;" type="text" size="small">编辑</el-button>
                          <!-- <el-button v-if="scope.row.isEdit" @click="saveSale(scope.row)" type="text" size="small">保存</el-button> -->
                          <el-button @click="delSale(scope.row, scope.$index)" type="text" size="small">删除</el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-tab-pane>
                  <el-tab-pane label="客户跟进" name="fourth">
                    <el-table :data="form.followList" border style="width: 100%;">
                      <el-table-column align="center" type="index" label="序号" width="60"></el-table-column>
                      <el-table-column prop="followPhaseName" align="center" label="跟进阶段" min-width="100"></el-table-column>
                      <el-table-column prop="customerStatusName" align="center" label="客户状态" min-width="100"></el-table-column>
                      <el-table-column prop="followResult" align="center" label="跟进内容" min-width="100"></el-table-column>
                      <el-table-column prop="followDate" align="center" label="跟进时间" min-width="100"></el-table-column>
                      <el-table-column label="操作" min-width="100" align="center">
                        <template slot-scope="scope">
                          <el-button  @click="openGj(scope.row, true)" type="text" size="small">查看</el-button>
                          <el-button v-if="!isObserver" @click="openGj(scope.row, false)" type="text" size="small">编辑</el-button>
                          <el-button v-if="!isObserver" @click="delGj(scope.row)" type="text" size="small">删除</el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-tab-pane>
                </el-tabs>
              </el-col>
            </el-row>
            <el-form-item>
              <el-button style="float:right;" size="small" @click="showForm = false">关闭</el-button>
              <el-button v-if="!isCheck" style="float:right;margin-right: 10px;" size="small" type="primary" @click="saveForm">保存</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-dialog>
      <el-dialog width="1000px" :visible.sync="showGj" :show-close="true">
        <div slot="title">
          <h2 style="text-align:center;margin-bottom:0;">{{gjform.id? isGjCheck? '查看': '编辑': '新增'}}跟进</h2>
        </div>
        <div class="form-wrapper" style="padding: 0 20px;">
          <el-form :model="gjform" label-width="100px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item style="font-weight: bold;" label="客户：">
                  <el-input disabled type="text" v-model="gjform.customerName"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item style="font-weight: bold;" label="跟进时间：">
                  <el-date-picker :disabled="isGjCheck" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" v-model="gjform.followDate" style="width: 100%;"></el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item style="font-weight: bold;" label="跟进阶段：">
                  <el-select :disabled="isGjCheck" style="width: 100%;" v-model="gjform.followPhase" placeholder="请选择跟进阶段">
                    <el-option v-for="item in gjzt" :key="item.id" :label="item.name" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item style="font-weight: bold;" label="客户状态：">
                  <el-select :disabled="isGjCheck" style="width: 100%;" v-model="gjform.customerStatus" placeholder="请选择客户状态">
                    <el-option v-for="item in khzt" :key="item.id" :label="item.name" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item style="font-weight: bold;" label="订单号：">
                  <el-input :disabled="isGjCheck" type="text" v-model="gjform.orderNo"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item style="font-weight: bold;" label="跟进结果：">
                  <el-input :disabled="isGjCheck" type="textarea" :rows="3" placeholder="请输入任务内容" v-model="gjform.followResult"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item>
              <el-button style="float:right;" size="small" @click="showGj = false">关闭</el-button>
              <el-button v-if="!isGjCheck" style="float:right;margin-right: 10px;" size="small" type="primary" @click="saveGjForm">保存</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-dialog>
    </div>
    <Email ref="email"/>
  </div>
</template>

<script>
import dingMixin from "@/mixins/ding";
import formUtil from "@/utils/formUtil";
import {dateUtil} from '@/utils/dateUtil'
import Email from '../email/Email.vue'

export default {
  data() {
    return {
      timesort: '',
      showGj:false,
      activeName: 'first',
      showPeopleBtn: false,
      showFilter: false,
      loading:false,
      showForm: false,
      tableHeight: window.tableHeight,
      tableData: [],
      page:1,
      pageSize: 15,
      totalPage: 1,
      gjform: {
        customerNo: '',
        customerName: '',
        customerId: '',
        followResult: '',
        followDate: '',
        followPhase: '',
        content: '',
        orderNo: ''
      },
      form: {
        id: '',
        name: '',
        code: '',
        levelCode: '',
        countryCode: '',
        countryName: '',
        company: '',
        fromPlatId: '',
        fromPlat: '',
        salorId: '',
        salorName: '',
        aliaName: '',
        businessType: '',
        customerStatus: '',
        customerType: '',
        timeZone: '',
        remark: '',
        customerStatus: '',
        createDate: '',
        contactList:[],
        accList:[],
        addrList:[],
        city: '',
        companyId: '',
        companyEntity: ''
      },
       formVerify: {
        name: '请输入客户名称',
        customerType: '请选择客户类型',
        countryCode: '请选择国家',
        levelCode: '请选择客户等级'
      },
      custormerList: [],
      filterData: {
        search: '',
        customerCode: '',
        fromPlatId: '',
        customerType: '',
        customerStatus: '',
        countryCode: '',
      },
      ywlx: [],
      khlx: [],
      khly: [],
      gjdq: [],
      khdj: [],
      khzt: [],
      isCheck: false,
      sq: [{
        name:'GTM'
      },{
        name:'GTM+01:00'
      },{
        name:'GTM+02:00'
      },{
        name:'GTM+03:00'
      },{
        name:'GTM+04:00'
      },{
        name:'GTM+05:00'
      },{
        name:'GTM+06:00'
      },{
        name:'GTM+07:00'
      },{
        name:'GTM+08:00'
      },{
        name:'GTM+09:00'
      },{
        name:'GTM+10:00'
      },{
        name:'GTM+11:00'
      },{
        name:'GTM+12:00'
      },{
        name:'GTM+13:00'
      },{
        name:'GTM+14:00'
      },{
        name:'GTM+15:00'
      },{
        name:'GTM+16:00'
      },{
        name:'GTM+17:00'
      },{
        name:'GTM+18:00'
      },{
        name:'GTM+19:00'
      },{
        name:'GTM+20:00'
      },{
        name:'GTM+21:00'
      },{
        name:'GTM+22:00'
      },{
        name:'GTM+23:00'
      }],
      lxfs: [],
      gjzt: [],
      companysList: [],
      multipleSelection: [],
      shareMember: {
        ids: [],
        names: []
      },
      allDict: [],
      isGjCheck: false,
      formVerifyGj: {
        customerId: '请输入客户名称',
        followResult: '请输入跟进结果',
        followPhase: '请选择跟进阶段',
        followDate: '请输入跟进日期',
        customerStatus: '请选择客户状态',
      },
      ssgs: []
    }
  },
  components: {
    Email
  },
  computed: {
    isObserver() {
      return this.userInfo.roleIdList && this.userInfo.roleIdList.includes('1289086254290432001')
    },
    isManager() {
      return this.userInfo.roleIdList && this.userInfo.roleIdList.includes('1289086160891670529')
    }
  },
  mixins: [dingMixin],
  mounted() {
    this.$nextTick(() => {
      this.tableHeight = document.documentElement['clientHeight'] - 170;
    })
    window.onresize = () => {
      this.tableHeight = document.documentElement['clientHeight'] - 170
    }
    
    this.getALLDict();
    this.searchItem(true);
  },
  methods: {
    endEmail(name) {
      this.$refs.email.openEmail({name: name}, 'kh');
    },
    async fetchSSGS(query) {
      if (query !== '') {
        this.loading = true;
        let data = await this.$httpN.postB('crm/company/list',{
          name: query,
          page: 1,
          limit: 99,
        })
        this.loading = false;
        this.ssgs = data.list;
      } else {
        this.ssgs = [];
      }
    },
    handleSelect(id) {
      this.form.companyEntity = this.ssgs.filter(item => item.id === id)[0];
    },
    sortList(sort) {
      this.timesort = sort.order === 'ascending'? 1: sort.order === 'descending'? -1 : '';
      this.searchItem(true);
    },
    async saveGjForm() {
      if(!formUtil.verifyData(this.gjform, this.formVerifyGj)) return;
      if(!await this.$httpN.postB('crm/customerfollow/save', this.gjform)) return;
      formUtil.submitSuccess('成功');
      this.showGj = false;
      this.editCustomer(this.form.id, this.isCheck, 'fourth')
    },
    clickFileBtn() {
      this.$refs.uploadbtn.click();
    },
    uploadCustomer(e) {
      let file = e.target.files[0];
      var formData = new FormData();
      formData.append("file", file);
      formData.append("name", 'file');
      this.$httpN.upload('crm/customer/upload', formData, 'blob').then((res) => {
        if(res.data.size === 0) {
          formUtil.submitSuccess('上传成功')
          this.searchItem(true);
        }else{
          this.$message.error('部分内容导入失败')
          this.downFile(res.data, '无法导入的客户.xls')
        }
      })
      e.target.value = '';
    },
    async giveCustomer() {
      this.complexPicker(1, [], []).then(
        async data => {
          let ids = this.multipleSelection.map(item => item.id);
          if(!await this.$httpN.postB('crm/customer/give', {ids, salorId: data[0].emplId, salorName: data[0].name})) return;
          formUtil.submitSuccess('转交成功');
          this.searchItem();
        }
      );
    },
    delGj(target) {
      let ids = [target.id];
      formUtil.submitConfirm('您确定要删除跟进吗？', async ()=> {
        if(!await this.$httpN.postB('crm/customerfollow/delete', ids, false)) return;
        formUtil.submitSuccess('删除成功');
        this.editCustomer(this.form.id, this.isCheck, 'fourth')
      })
    },
    openGj(target, check) {
      this.gjform = formUtil.deepCopy(target);
      this.isGjCheck = check;
      if(this.gjform.customerName) this.custormerList = [{name: this.gjform.customerName, id: this.gjform.customerId, code: this.gjform.customerNo}];
      this.showGj = true;
    },
    delShareMember(idx) {
      this.shareMember.ids.splice(idx, 1);
      this.shareMember.names.splice(idx, 1);
    },
    async selectShareMember() {
      this.complexPicker(20, [], this.shareMember.ids).then(
        async data => {
          this.shareMember.ids = data.map(item => item.emplId);
          this.shareMember.names = data.map(item => item.name);
        }
      );
    },
    async shareCustomer() {
      this.complexPicker(20, [], []).then(
        async data => {
          let shareIds = data.map(item => item.emplId);
          let shareNames = data.map(item => item.name);
          let ids = this.multipleSelection.map(item => item.id);
          if(!await this.$httpN.postB('crm/customer/share', {ids: ids, shareUsers: shareIds.join(','), shareUsersName: shareNames.join(',')}, false)) return;
          formUtil.submitSuccess('共享成功');
          this.searchItem();
        }
      );
    },
    async editCustomer(id, isCheck, target = 'first') {
      this.activeName = target;
      let form = await this.$httpN.get('crm/customer/info/' + id);
      form.addrList.forEach(item => {item.isEdit = false;})
      form.contactList.forEach(item => {item.isEdit = false;})
      form.accList.forEach(item => {item.isEdit = false;})
      this.isCheck = isCheck;
      if(form.companyId) this.ssgs = [formUtil.deepCopy(form.companyEntity)];
      if(form.shareUsers) {
        this.shareMember.ids = form.shareUsers.split(',');
        this.shareMember.names = form.shareUsersName.split(',');
      }else {
        this.shareMember.ids = [];
        this.shareMember.names = [];
      }
      this.form = form;
      this.showForm = true;
    },
    async delCustomer(id) {
      let ids = id ? [id]: this.multipleSelection.map(item => item.id);
      formUtil.submitConfirm('您确定要删除客户吗？', async ()=> {
        if(!await this.$httpN.postB('crm/customer/delete', ids, false)) return;
        formUtil.submitSuccess('删除成功');
        this.searchItem(true);
      })
    },
    openAddForm() {
      if(this.activeName === 'first'){
        this.form.addrList.push({
          customerId: this.form.id,
          recName: '',
          recAddr: '',
          postalCode: '',
          company: '',
          email: '',
          phone: '',
          taxNo: '',
          isEdit: true
        })
      }else if(this.activeName === 'second'){
        this.form.contactList.push({
          customerId: this.form.id,
          contactType: '',
          content: '',
          isEdit: true
        })
      }else if(this.activeName === 'third'){
        this.form.accList.push({
          customerId: this.form.id,
          swiftCode: '',
          accountNo: '',
          bankName: '',
          enName: '',
          bankAddr: '',
          bankTel: '',
          accountName: '',
          remark: '',
          isEdit: true
        })
      }else if(this.activeName === 'fourth') {
        this.showGj = true;
        this.isGjCheck = false;
        this.gjform = {
          customerNo: this.form.code,
          customerName: this.form.name,
          customerId: this.form.id,
          followResult: '',
          followDate: '',
          followPhase: '',
          content: '',
          orderNo: ''
        }
      }
    },
    async delSale(item, idx) {
      if(this.activeName === 'first'){
        this.form.addrList.splice(idx, 1)
      }else if(this.activeName === 'second'){
        this.form.contactList.splice(idx, 1)
      }else if(this.activeName === 'third'){
        this.form.accList.splice(idx, 1)
      }
    },
    async saveSale(item) {
      if(this.activeName === 'first'){
        let id = await this.$httpN.postB('crm/customeraddr/save', item);
        if(!item.id) item.id = id;
        formUtil.submitSuccess('保存成功');
        item.isEdit = false;
      }else if(this.activeName === 'second'){
        let id = await this.$httpN.postB('crm/crmcustomercontact/save', item);
        if(!item.id) item.id = id;
        formUtil.submitSuccess('保存成功');
        item.isEdit = false;
      }else if(this.activeName === 'third'){
        let id = await this.$httpN.postB('crm/customeraccount/save', item);
        if(!item.id) item.id = id;
        formUtil.submitSuccess('保存成功');
        item.isEdit = false;
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    removeItem(idx) {
      this.form.contactList.splice(idx,1) 
    },
    addItem(idx) {
      this.form.contactList.splice(idx+1, 0, {
        contactType: '',
        content: ''
      }) 
    },
    createCustomer() {
      this.showForm = true;
      this.isCheck = false;
      this.activeName = 'first';
      formUtil.resetData(this.form);
      this.form.salorId = this.userInfo.dingId;
      this.form.salorName = this.userInfo.realName;
      this.form.contactList.push({
        contactType: '',
        content: ''
      })
    },
    async getALLDict() {
      this.ywlx = await this.getDict('1291997592096690177')
      this.khlx = await this.getDict('1291997623520415745')
      this.khly = await this.$httpN.get('crm/dict/customerPlat');
      this.gjdq = await this.$httpN.postQ('mpb/market/listCountry')
      this.khzt = await this.getDict('1291997539810496513')
      this.khdj = await this.$httpN.postQ('mpb/customer/listLevel')
      this.lxfs = await this.getDict('1292642135951065090')
      this.gjzt = await this.getDict('1291997498622431234')
    },
    async getDict(pid) {
      if(this.allDict.length === 0) this.allDict = await this.$httpN.postQ('crm/dict/list');
      return this.allDict.filter(item => item.pid === pid);
    },
    getFilterData() {
      this.searchItem(true);
      this.showFilter = false;
    },
    resetData() {
      formUtil.resetData(this.filterData)
    },
    openApprovalDialog() {

    },
    getPic(filename) {
      if(filename) {
        if(/\.(bmp|gif|jpg|pic|png|tif|jpeg)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276438103037435905.png'
        }else if(/\.(txt)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276438530785140737.png'
        }else if(/\.(xls|xlsx)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276438725690253314.png'
        }else if(/\.(doc|docx)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276439195636850689.png'
        }else if(/\.(psd)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276439984203751426.png'
        }else if(/\.(pdf)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276440139145535490.png'
        }else if(/\.(ppt|pptx|dps|dpt)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276440657859305473.png'
        }else if(/\.(rar|zip|arj|gz)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276442063039193090.png'
        }else if(/\.(html|htm)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276442135319633921.png'
        }else if(/\.(dwg|bak|dwt)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276441741667459074.png'
        }else if(/\.(wav|aif|au|mp3|ram|wma|mmf)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276442006684524546.png'
        }else if(/\.(avi|mov|rmvb|rm|flv|mp4)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276442233483124737.png'
        }else{
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276436590181343234.png'
        }
      }else {
        return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276436590181343234.png'
      }
    },
    delFile(idx){
      this.form.attachments.splice(idx, 1)
    },
    async uploadFile(e) {
      var files = e.target.files;
      var $this = this;
      Object.keys(files).forEach(function(key){
        var file = files[key];
        if(file.size / 1024 / 1024 > 20) return $this.mobileAlert('上传单个文件大小不能超过20MB!请压缩文件')
        var formData = new FormData();
        formData.append("file", file);
        formData.append("name", 'file');
        let newfile = {
          name: file.name,
          url: '',
          size: file.size,
          uploader: $this.userInfo.realName,
          time: dateUtil.thisDay()
        }
        $this.form.attachments.push(newfile)
        $this.$httpN.upload('fileUpload', formData).then(res => {
          if(res.data.code === 0) {
            newfile.url = res.data.url;;
          }else if(res.data.code === 500) {
            $this.form.attachments.pop();
          }
        })
      })
      e.target.value = '';
    },
    selectDingUsers() {
      this.complexPicker(1, [], []).then(
        data => {
          this.form.salorId = data[0].emplId;
          this.form.salorName = data[0].name;
        }
      );
    },
    delMember() {
      this.form.salorId = '';
      this.form.salorName = '';
    },
    async saveForm() {
      if(this.form.id) {
        this.form.shareUsersName = this.shareMember.names.join(',');
        this.form.shareUsers = this.shareMember.ids.join(',');
      }
      if(!formUtil.verifyData(this.form, this.formVerify)) return;
      let pass = true;
      this.form.accList.forEach((item) => {
        if(item.swiftCode === '') pass = false;
      })
      if(!pass) return this.$message.error('请输入银行识别码');
      this.form.contactList = this.form.contactList.filter((item) => !!item.content);
      let postForm = formUtil.deepCopy(this.form);
      delete postForm.companyEntity;
      if(!await this.$httpN.postB('crm/customer/save', postForm)) return;
      this.showForm = false;
      formUtil.submitSuccess('保存成功');
      this.searchItem(true);
    },
    async remoteMethod(query) {
      if (query !== '' && query.length >= 2) {
        this.loading = true;
        this.custormerList = await this.$httpN.postQ('mpb/customer/getByName', {name: query});
        this.loading = false;
      } else {
        this.custormerList = [];
      }
    },
    sizeChangeHandle(limit) {
      this.pageSize = limit;
      this.searchItem(true);
    },
    currentChangeHandle(page) {
      this.page = page;
      this.searchItem();
    },
    async searchItem(init) {
      if(init) this.page = 1;
      let data = await this.$httpN.postB('crm/customer/list',{
        search: this.filterData.search,
        customerCode: this.filterData.customerCode,
        fromPlatId: this.filterData.fromPlatId,
        customerType: this.filterData.customerType,
        customerStatus: this.filterData.customerStatus,
        countryCode: this.filterData.countryCode,
        searchType: 'public',
        page: this.page,
        timesort: this.timesort,
        limit: this.pageSize,
      })
      this.tableData = data.list;
      this.totalPage = data.totalCount
    },
    async exportExcel() {
      let data = await this.$httpN.get('crm/customer/export', {
        search: this.filterData.search,
        customerCode: this.filterData.customerCode,
        fromPlatId: this.filterData.fromPlatId,
        customerType: this.filterData.customerType,
        customerStatus: this.filterData.customerStatus,
        countryCode: this.filterData.countryCode,
        searchType: 'public',
      }, 'blob')

      this.downFile(data, `客户信息.xls`);
    },
    downFile(blob, fileName) {
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, fileName);
      } else {
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = fileName;
        link.click();
        window.URL.revokeObjectURL(link.href);
      }
    },
    downloadTemplate() {
      var x = new XMLHttpRequest();
      x.open("GET", 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1303585132326699009.xls', true);
      x.responseType = 'blob';
      x.onload=function(e) {
        var url = window.URL.createObjectURL(x.response)
        var a = document.createElement('a');
        a.href = url
        a.download = '客户模板';
        a.click()
      }
      x.send();
    }
  }
}
</script>

<style lang="scss" scoped>
  .header{
    position: relative;
    padding: 10px 0 0 20px ;
    .filter{
      cursor: pointer;
      float: right;
      margin-right: 30px;
      line-height: 30px;
      img{
        width: 16px;
        margin-right: 3px;
      }
    }
    .mask{
      position: fixed;
      height: 100vh;
      width: 100%;
      top: 0;
      right: 0;
      z-index: 3;
    }
    .filter-wrapper{
      position: absolute;
      width: 315px;
      padding-bottom: 20px;
      background: white;
      top: 48px;
      right: 20px;
      z-index: 99;
      border-radius: 5px;
      box-shadow: 0 0 3px black;
      .filter-header{
        line-height: 40px;
        padding-left: 16px;
        border-bottom: 1px solid #DDD;
        margin-bottom: 20px;
      }
      .filter-arrow{
        width:12px;
        height:12px;
        position: absolute;
        top: -7px;
        right: 20px;
        box-shadow: 0 0 3px black;
        transform: rotate(45deg);
      }
      .filter-white{
        width:18px;
        height:18px;
        position: absolute;
        top: -2px;
        right: 17px;
        border-radius: 3px;
        background: white;
      }
    }
  }
  .data-wrapper{
    padding: 0 20px;
    margin-top: 10px;
  }
  .select-btn{
    display: inline-block;
    font-weight: normal;
    margin-right: 5px;
    width: 80px;
    height: 28px;
    border-radius: 30px;
    background: #FAFAFA;
    border: 1px solid #ECECEC;
    position: relative;
    line-height: 28px;
    color: #7982A7;
    font-size: 12px;
    text-align: center;
    position: relative;
    cursor: pointer;
    .del{
      position: absolute;
      top:0;
      left: 0;
      width: 100%;
      height: 100%;
      border-radius: 30px;
      color: white;
      text-align: center;
      background:rgba(130, 130, 130, 0.9);
      display: none;
    }
    &:hover{
      .del{
        display: block;
      }
    }
  }
  .fileitem{
    line-height: 32px;
    margin-bottom: 5px;
    background: #F5F5F5;
    width: 474px;
    padding-left:15px;
    font-size: 12px;
    .uploadtip{
      float:right;
      margin-right: 20px;
      cursor: pointer;
    }
  }
  .addfilebtn{
    cursor: pointer;
    color: #909399;
    display: block;
    font-weight: normal;
  }
</style>